﻿//NorManager - OpenTTD Dedicated server manager
//Copyright (C) 2014 Tomáš Bosek

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.IO;

using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace NorManager
{
    /// <summary>
    /// Parsing and executing Python scripts.
    /// </summary>
    class PythonScripts
    {
        private ScriptEngine engine = null;
        private ScriptScope scope = null;

        private string[] scriptList;
        /// <summary>
        /// Loading scripts and preparing for executing. May take a little time.
        /// </summary>
        /// <param name="prefix">Prefix of script name</param>
        internal void LoadScripts(string prefix)
        {
            if (!Directory.Exists("scripts"))
                Directory.CreateDirectory("scripts");

            scriptList = Directory.GetFiles("scripts", prefix+"*.py");

            engine = Python.CreateEngine();
            scope = engine.CreateScope();
            engine.Execute(
                "import clr\n" +
                "clr.AddReference(\"NorManager\")\n" +
                "import sys\n" +
                "sys.path.append(\"IronPython-2.7.4/Lib/\")");

            Logger.Instance.Log(String.Format("Loaded {0} {1}scripts.", scriptList.Length, prefix));
        }

        /// <summary>
        /// Scripts are going to be executed every StartSession period.
        /// </summary>
        internal void ExecuteScripts()
        {
            foreach (string script in scriptList)
            {
                try
                {
                    ScriptSource source = engine.CreateScriptSourceFromFile(script);
                    source.Execute();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log(String.Format("Script {0} thrown an exception: {1}", Path.GetFileName(script), ex.ToString()));
                }
            }
        }
    }
}
